package a09_贪心算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a20_合并区间
 * </p>
 *
 * @author flyduck
 * @since 2025/1/16
 */
public class a20_合并区间 {
    public static void main(String[] args) {
//        int[][] merge = merge(new int[][]{
//                {1, 3}, {2, 6}, {8, 10}, {15, 18}
//        });
        int[][] merge = merge(new int[][]{
                {1,10},{2,3},{4,5},{6,7},{8,9}
        });
        System.out.println();
    }
    //有重叠的进行合并
    public static int[][] merge(int[][] intervals) {
        intervals = Arrays.stream(intervals)
                .sorted((item1,item2) -> {
                    if(item1[0] > item2[0]){
                        return 1;
                    }else if(item1[0] < item2[0]){
                        return -1;
                    }else {
                        return 0;
                    }
                }).toArray(int[][]::new);

        LinkedList<int[]> result = new LinkedList<>();
        result.add(intervals[0]);
        for (int i = 1; i < intervals.length; i++) {
            if(intervals[i][0] <= intervals[i-1][1]){//重叠了
                int[] ints = result.removeLast();
                ints[1] = Math.max(ints[1], intervals[i][1]);
                result.add(ints);
                intervals[i][1] = ints[1];
            }else {
                result.add(intervals[i]);
            }
        }
        return result.stream().toArray(int[][]::new);
    }
}
